#include "dg_echo.h"
#include <define.h>
#include <error.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <sysfunc.h>
#include <signal.h>
#include <stdlib.h>


void 
dg_echo(int sockfd, struct sockaddr *sa, socklen_t salen) {
	char buf[MAX_LINE];
	socklen_t len;
	ssize_t n;
	for (;;) {
		len = salen;
		n = Recvfrom(sockfd, buf, sizeof(buf)-1, 0, sa, &len);
        error_msg("recv data from:%s", sock_ntop(sa, len));
		Sendto(sockfd, buf, n, 0, sa, len);
	}
}

static int _count = 0;
static void
_sig_func(int signo) {
    error_msg("total recv %d datagram", _count);
    exit(0);
    (void)signo;
}

void 
dg_echoloop1(int sockfd, struct sockaddr *sa, socklen_t salen) {
    Signal(SIGINT, _sig_func);

	char buf[MAX_LINE];
	socklen_t len;
	for (;;) {
		len = salen;
		Recvfrom(sockfd, buf, sizeof(buf), 0, sa, &len);
        _count++;
	}
}

void 
dg_echoloop2(int sockfd, struct sockaddr *sa, socklen_t salen) {
    Signal(SIGINT, _sig_func);

    // 增加接收缓冲区，减少 udp 因缓冲区满而丢包
    int n = 220 * 1024;
    Setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));

	char buf[MAX_LINE];
	socklen_t len;
	for (;;) {
		len = salen;
		Recvfrom(sockfd, buf, sizeof(buf), 0, sa, &len);
        _count++;
	}
}

